﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using System.Diagnostics;

namespace Tesla.Core {
    /// <summary>
    /// GameTimer is a timer used for interpolation. When the timer is updated
    /// it returns a GameTime object that represents the current snapshot of
    /// the simulation - elapsed time from the last update call, and the total
    /// time the simulation has been running. This does not necessarily
    /// reflect real time, since the timer can be paused.
    /// </summary>
    public sealed class GameTimer {
        private GameTime _gameTime;

        private long _startTime;
        private long _prevTime;

        private bool _isRunning;
        private bool _wasPaused;

        private long _pauseStart;
        private long _timePaused;

        private long _frequency;

        /// <summary>
        /// Gets the game time snapshot.
        /// </summary>
        public GameTime GameTime {
            get {
                return _gameTime;
            }
        }

        /// <summary>
        /// Create a new instance of the game timer.
        /// </summary>
        public GameTimer() {
            _gameTime = new GameTime(TimeSpan.Zero, TimeSpan.Zero);
            _frequency = Stopwatch.Frequency;
            Reset();
        }

        /// <summary>
        /// Start the timer.
        /// </summary>
        public void Start() {
            if(!_isRunning) {
                Reset();
                _prevTime = Stopwatch.GetTimestamp();
                _startTime = _prevTime;
                _isRunning = true;
            }
        }

        /// <summary>
        /// Pause the timer.
        /// </summary>
        public void Pause() {
            if(_isRunning) {
                _isRunning = false;
                _wasPaused = false;

                _pauseStart = Stopwatch.GetTimestamp();
            }
        }

        /// <summary>
        /// Resume the timer.
        /// </summary>
        public void Resume() {
            if(!_isRunning) {
                _isRunning = true;
                _wasPaused = true;

                _timePaused += Stopwatch.GetTimestamp() - _pauseStart;
                _pauseStart = 0L;
            }
        }

        /// <summary>
        /// Reset the timer. The timer will be invalid until it is started.
        /// </summary>
        public void Reset() {
            _isRunning = _wasPaused = false;
            _prevTime = _startTime = _pauseStart = _timePaused = 0L;
        }

        /// <summary>
        /// Advance and update the timer.
        /// </summary>
        /// <returns>GameTime that represents the current time snapshot</returns>
        public GameTime Update() {
            long currTime = Stopwatch.GetTimestamp();

            if(!_isRunning) {
                _gameTime.ElapsedGameTime = TimeSpan.Zero;
                _gameTime.ElapsedTimeInSeconds = 0d;
                return _gameTime;
            } else if(_wasPaused) {
                TimeSpan elapsedTime = CreateTimeSpan(currTime - (_prevTime + _timePaused));
                _timePaused = 0L;
                _gameTime.ElapsedGameTime = elapsedTime;
                _gameTime.TotalGameTime += elapsedTime;
                _gameTime.ElapsedTimeInSeconds = elapsedTime.TotalSeconds;
                _prevTime = currTime;
                _wasPaused = false;
                return _gameTime;
            } else {
                TimeSpan elapsedTime = CreateTimeSpan(currTime - _prevTime);
                _gameTime.ElapsedGameTime = elapsedTime;
                _gameTime.TotalGameTime += elapsedTime;
                _gameTime.ElapsedTimeInSeconds = elapsedTime.TotalSeconds;

                _prevTime = currTime;
                return _gameTime;
            }
        }

        private TimeSpan CreateTimeSpan(long ticks) {
            long time = (ticks * 10000000L) / _frequency;
            return TimeSpan.FromTicks(time);
        }
    }
}
